<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片上传</title>
    <link rel="stylesheet" type="text/css" href="/static/webuploader/webuploader.css">
    <link rel="stylesheet" type="text/css" href="/static/bootstrap-4.5.0-dist/css/bootstrap.min.css">
    <script src="/static/js/jquery.min.js"></script>
     <script src="/static/js/jquery.cookie.js"></script>
    <script src="/static/webuploader/webuploader.min.js"></script>
    <script type="text/javascript" src="/static/js/HashMap.js"></script>
    <style type="text/css">
        #picker{
            display: inline-block;
            line-height: 1.428571429;
            vertical-align: middle;
            margin: 0 12px 0 0;
        }
    </style>
</head>
<body>
    <div id="uploader" class="container">
        <div id="thelist" class="row">
            <div class="panel panel-primary">
                <div class="panel-heading">文件上传</div>
                <table class="table table-striped table-bordered" id="uploadTable">
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th>文件名称</th>
                            <th>文件大小</th>
                            <th>上传状态</th>
                            <th>上传进度</th>
                            <th style="width: 15%;">操作</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
                <div class="panel-footer">
                    <div id="picker">选择文件</div>
                    <button id="btn" class="btn btn-default">开始上传</button>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        var fileMd5;
        var fileSuffix;
        var $list = $("#thelist table>tbody");
        var state = 'pending';
        var $btn = $("#btn");
        var count = 0;
        var map = new HashMap();
        var csrftoken =  $.cookie('csrftoken');
        //监听上传的三个点
        WebUploader.Uploader.register({
            "before-send-file" : "beforeSendFile",
            "before-send" : "beforeSend",
            "after-send-file":"afterSendFile",
        },{
            //1*******
            beforeSendFile : function (file) {
                var deferred = WebUploader.Deferred();
                //1、计算文件的唯一标记，用于断点续传
			    // (new WebUploader.Uploader()).md5File(file, 0, 10 * 1024 * 1024)
                (new WebUploader.Uploader()).md5File(file, 0, 1024)
                    .progress(function (percentage) {
                        $('#'+file.id).find("td.state").text("正在读取文件信息...");
                    }).then(function (val) {
                        fileMd5 = val;
                        $('#'+file.id).find("td.state").text("成功读取文件信息...");
                        deferred.resolve();
                    })
                return deferred.promise();
            },
             //2******如果有分块上传，则每个分块上传之前调用此函数
            beforeSend : function (block) {
                var deferred = WebUploader.Deferred();
                $.ajax({
                    type : 'POST',
                    url : "{% url 'img:checkChunk' %}",
                    headers: {"X-CSRFToken": csrftoken},
                    data : {
                        //文件唯一标记
                        fileMd5 : fileMd5,
					    //当前分块下标
                        chunk : block.chunk,
					    //当前分块大小
					    chunkSize : block.end - block.start
                    },
                    dataType : "json",
                    success : function (response) {
                        if (response.ifExist){
                            deferred.reject();
                        } else {
                            deferred.resolve();
                        }
                    }
                });
                this.owner.options.formData.fileMd5 = fileMd5;
                deferred.resolve();
                return deferred.promise();
            },
            //3******所有分块上传成功后调用此函数
            afterSendFile : function (file) {
                $.ajax({
                    type: "POST",
                    url: "{% url 'img:mergeChunks' %}",
                    data: {
                        fileId : file.id,
					    fileMd5 : fileMd5,
					    fileSuffix:fileSuffix,
					    fileName:file.name,
                    },
                    headers: {"X-CSRFToken": csrftoken},
                    success: function (response) {
                        console.log(response.fileName+" 上传成功")
					    $('#del'+file.id).hide();
                    }
                })
            }
        });

        var uploader = WebUploader.create({
            swf: '/static/webuploader/Uploader.swf',
            server: "{% url 'img:upload' %}",
            pick: {
                id: '#picker',
                multiple: true
            },
            resize: false,//尺寸不改变
            compress: false,//不启用压缩
            checked: true,
            auto: true,
            chunkSize: 10 * 1024 * 1024,
            headers: {"X-CSRFToken": csrftoken},
            accent: {
                extensions : "txt,jpg,jpeg,bmp,png,zip,rar,war,pdf,cebx,doc,docx,ppt,pptx,xls,xlsx,iso,flv,mp4",
                mimeTypes : '.txt,.jpg,.jpeg,.bmp,.png,.zip,.rar,.war,.pdf,.cebx,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.iso,.flv,.mp4'
            }

        });

        // 当有文件被添加进队列的时候
	  uploader.on('fileQueued', function(file) {
		  //保存文件扩展名
		  fileSuffix=file.ext;
		  fileName=file.source['name'];
		  var fileSize=file.size;
		  var fileSizeStr="";
		  fileSizeStr=WebUploader.Base.formatSize(fileSize);
		  count++;
		  $list.append(
				  '<tr id="' + file.id + '" class="item" flag=0>'+
				  '<td class="index">' + count + '</td>'+
				  '<td class="info">' + file.name + '</td>'+
				  '<td class="size">' + fileSizeStr + '</td>'+
				  '<td class="state">等待上传...</td>'+
				  '<td class="percentage"></td>'+
				  '<td class="operate"><button name="upload" id="del'+file.id+'" class="btn btn-warning">开始</button><button name="delete" class="btn btn-error">删除</button></td></tr>');
		  map.put(file.id+"",file);
	  });

	  // 文件上传过程中创建进度条实时显示。
	  uploader.on('uploadProgress', function(file, percentage) {
		  $('#' + file.id).find('td.percentage').text(
				  '上传中 ' + Math.round(percentage * 100) + '%');
	  });

	  uploader.on('uploadSuccess', function(file) {
		  $('#' + file.id).find('td.state').text('已上传');
	  });

	  uploader.on('uploadError', function(file) {
		  $('#' + file.id).find('td.state').text('上传出错');
	  });

	  uploader.on('uploadComplete', function(file) {
		  uploader.removeFile(file);
	  });


	  uploader.on('all', function(type) {
		  if (type === 'startUpload') {
			  state = 'uploading';
		  } else if (type === 'stopUpload') {
			  state = 'paused';
		  } else if (type === 'uploadFinished') {
			  state = 'done';
		  }

		  if (state === 'uploading') {
			  $btn.text('暂停上传');
		  } else {
			  $btn.text('开始上传');
		  }
	  });

	  $btn.on('click', function(){
		  if (state === 'uploading'){
			  uploader.stop(true);
		  } else {
			  uploader.upload();
		  }
	  });

	  $("body").on("click","#uploadTable button[name='upload']",function(){
		  flag=$(this).parents("tr.item").attr("flag")^1;
		  $(this).parents("tr.item").attr("flag",flag);
		  var id=$(this).parents("tr.item").attr("id");
		  if(flag == 1){
			  $(this).text("暂停");
			  uploader.upload(uploader.getFile(id,true));

		  }else {
              $(this).text("开始");
              uploader.stop(uploader.getFile(id, true));
          }
	  });

	  $("body").on("click","#uploadTable button[name='delete']",function(){
		  var id=$(this).parents("tr.item").attr("id");
		  $(this).parents("tr.item").remove();
		  uploader.removeFile(uploader.getFile(id,true));
		  map.remove(id);
	  });
    </script>
</body>
</html>